from django.conf import settings
from django_redis import get_redis_connection
from lyapi.settings.contains import CREDIT_TO_MONEY
def jwt_response_payload_handler(token, user=None, request=None):
    """
    自定义jwt认证成功返回数据
    """
    user_id = user.id
    conn = get_redis_connection('cart')
    cart_len = conn.hlen(user_id)

    return {
        'token': token,
        'id': user_id,
        'username': user.username,
        'cart_len': cart_len,
        'credit':user.credit,
        'credit_to_money':CREDIT_TO_MONEY,
    }

def get_user_obj_by_account(account):
    try:
        user = models.User.objects.get(Q(username=account) | Q(phone=account))
        print(user)
        return user
    except models.User.DoesNotExist:
        return None

from urllib.parse import urlencode
from urllib.request import urlopen
import json
import logging
logger = logging.getLogger('django')

def txrequest(Ticket,Randstr,UserIP):
    params = {
        "aid":settings.TENCENT_CAPTCHA.get('APPID'),
        'AppSecretKey':settings.TENCENT_CAPTCHA.get('App_Secret_Key'),
        'Ticket':Ticket,
        'Randstr':Randstr,
        'UserIP':UserIP
    }
    url = settings.TENCENT_CAPTCHA.get('GATEWAY')
    params = urlencode(params).encode()
    f = urlopen(url,params)
    content = f.read()
    res = json.loads(content)
    print(res)
    if res:
        error_code = res["response"]
        if error_code == "1":
            return True
        else:
            logger.warning("%s:%s" % (res["response"],res["err_msg"]))
            return False
    else:
        logger.warning("验证票据的相应数据有问题")
        return False


from django.conf import global_settings
from . import models
from django.db.models import Q
from django.contrib.auth.backends import ModelBackend


class CustomModelBackend(ModelBackend):

    def authenticate(self, request, username=None, password=None, **kwargs):
        # username可能是手机好，也可能是用户名
        print(kwargs)
        ticket = kwargs.get('ticket')
        if ticket:
            randstr = kwargs.get('ranstr')
            user_ip = request.META.get('REMOTE_ADDR')
            ret = txrequest(ticket,randstr,user_ip)
            print('111111',ticket,randstr,user_ip)
            if ret:
                user = get_user_obj_by_account(username)
                print(user)
                if user:
                    if user.check_password(password):
                        return user
        else:
            ret = super().authenticate(request,username=username,password=password,**kwargs)
            return ret